<template>
  <div class="wrapper">
    <div class="title">
      <h2>目录</h2>
      <span></span>
    </div>
    <ul class="index">
      <li v-for="(item, idx) in tree" :key="idx" @click="scrollTo(item.element)"
      :style="computeStyle(item.level)">
        {{computeString(item.title, item.level, '   ')}}
      </li>
    </ul>
  </div>
</template>

<script>
import { getIndexFromDomOrString } from '@/utils/parse.js';

  export default {
    props: {
      dom: {
        type: [Document, HTMLDivElement],
        default: () => null
      },
    },
    computed: {
      tree() {
        return getIndexFromDomOrString(this.dom);
      }
    },
    methods: {
      computeString(title, level, split) {
        return `${split.repeat(level)}${title}`
      },
      scrollTo(ele) {
        ele.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        });
      },
      computeStyle(level) {
        if(level === 0) {
          return {
            'fontWeight': 'bold'
          }
        } else {
          return {
            'textIndent': '20px'
          }
        }
      }
    },
  }
</script>

<style lang="less" scoped>
@w: var(--indexCardWidth);
@fs: calc(@w * 0.05);

.wrapper {
  width: @w;
  background-color: white;
  box-sizing: border-box;
  width: @w;
  padding: calc(@w * 0.04) calc(@w * 0.05);
  border-radius: calc(@w * 0.02);

  max-height: 420px;
  overflow-y: auto;

  .title {
    h2 {
      padding: calc(@w * 0.02) calc(@w * 0.04);
      font-size: calc(@fs * 1.2);
      line-height: 1.5;
      font-weight: bold;
    }

    span {
      display: block;
      height: 1px;
      background-color: var(--gray);

      margin:  0 0 calc(@w * 0.03) 0;
    }
  }

  .index {
    li {
      box-sizing: border-box;
      padding: calc(@w * 0.02) calc(@w * 0.04);
      border-radius: calc(@w * 0.02);
      font-size: calc(@fs * 1);

      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;

      &:hover {
        background-color: var(--slightBlue);
        color: var(--darkBlue);
        cursor: pointer;
      }
    }
  }
}
</style>